//! 协议层入口函数验证程序（独立版本）
//! 
//! 验证协议层直接接收NetworkStream并内部循环处理的设计

use std::io;

/// 网络流抽象trait - 协议层的核心依赖
trait NetworkStream: Send + Sync + std::fmt::Debug + 'static {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize>;
    fn write(&mut self, buf: &[u8]) -> io::Result<usize>;
    fn flush(&mut self) -> io::Result<()>;
    fn is_connected(&self) -> bool;
    fn remote_addr(&self) -> Option<String>;
    fn shutdown(&mut self) -> io::Result<()>;
    fn network_type(&self) -> &'static str;
}

/// 轻量级运行时抽象trait
trait LightweightRuntime: Send + Sync + 'static {
    fn spawn_task<F>(&self, task: F) where F: FnOnce() + Send + 'static;
    fn lightweight_type(&self) -> &'static str;
}

/// 线程池运行时实现
struct ThreadPoolRuntime;

impl LightweightRuntime for ThreadPoolRuntime {
    fn spawn_task<F>(&self, task: F) where F: FnOnce() + Send + 'static {
        std::thread::spawn(task);
    }
    fn lightweight_type(&self) -> &'static str { "ThreadPool" }
}

/// 模拟TCP网络流实现
#[derive(Debug)]
struct MockTcpStream {
    remote_addr: String,
    connected: bool,
    commands: Vec<Vec<u8>>,
    command_index: usize,
    responses: Vec<u8>,
}

impl MockTcpStream {
    fn new(remote_addr: String) -> Self {
        Self {
            remote_addr,
            connected: true,
            commands: vec![
                b"*1\r\n$4\r\nPING\r\n".to_vec(),
                b"*3\r\n$3\r\nSET\r\n$3\r\nkey\r\n$5\r\nvalue\r\n".to_vec(),
                b"*2\r\n$3\r\nGET\r\n$3\r\nkey\r\n".to_vec(),
            ],
            command_index: 0,
            responses: Vec::new(),
        }
    }
    
    fn get_responses(&self) -> String {
        String::from_utf8_lossy(&self.responses).to_string()
    }
}

impl NetworkStream for MockTcpStream {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.command_index >= self.commands.len() {
            self.connected = false;
            return Ok(0);
        }
        
        let command = &self.commands[self.command_index];
        let to_copy = std::cmp::min(buf.len(), command.len());
        buf[..to_copy].copy_from_slice(&command[..to_copy]);
        
        println!("📥 TCP读取数据: {} bytes - {}", to_copy, String::from_utf8_lossy(&command[..to_copy]));
        self.command_index += 1;
        
        Ok(to_copy)
    }
    
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.responses.extend_from_slice(buf);
        println!("📤 TCP写入响应: {} bytes - {}", buf.len(), String::from_utf8_lossy(buf));
        Ok(buf.len())
    }
    
    fn flush(&mut self) -> io::Result<()> {
        println!("🔄 TCP刷新缓冲区");
        Ok(())
    }
    
    fn is_connected(&self) -> bool { self.connected }
    fn remote_addr(&self) -> Option<String> { Some(self.remote_addr.clone()) }
    fn shutdown(&mut self) -> io::Result<()> { self.connected = false; Ok(()) }
    fn network_type(&self) -> &'static str { "Mock-TCP" }
}

/// 简化的RESP解析器
struct SimpleRespParser {
    buffer: Vec<u8>,
}

impl SimpleRespParser {
    fn new() -> Self {
        Self { buffer: Vec::new() }
    }
    
    fn feed_data(&mut self, data: &[u8]) {
        self.buffer.extend_from_slice(data);
    }
    
    fn parse_command(&mut self) -> Option<String> {
        let data = String::from_utf8_lossy(&self.buffer);
        
        // 简化的RESP解析 - 只识别基本命令
        if data.contains("PING") {
            self.buffer.clear();
            Some("PING".to_string())
        } else if data.contains("SET") {
            self.buffer.clear();
            Some("SET".to_string())
        } else if data.contains("GET") {
            self.buffer.clear();
            Some("GET".to_string())
        } else {
            None
        }
    }
}

/// 协议处理器 - 核心设计
struct ProtocolHandler<R: LightweightRuntime> {
    connection_id: u64,
    runtime: R,
    parser: SimpleRespParser,
}

impl<R: LightweightRuntime> ProtocolHandler<R> {
    fn new(connection_id: u64, runtime: R) -> Self {
        println!("🔧 创建协议处理器 {} (运行时: {})", 
                connection_id, runtime.lightweight_type());
        
        Self {
            connection_id,
            runtime,
            parser: SimpleRespParser::new(),
        }
    }
    
    /// 🎯 协议层入口函数 - 直接接收NetworkStream并内部循环处理
    /// 
    /// 这就是你要的设计：
    /// 1. 协议层直接接收NetworkStream trait对象
    /// 2. 协议层内部进行循环读取和解析
    /// 3. 网络层只需调用这一个函数
    fn handle_connection_stream(
        &mut self,
        mut stream: Box<dyn NetworkStream>,
    ) -> Result<(), String> {
        println!("🔄 协议层开始处理连接 {} (网络: {})", 
                self.connection_id, stream.network_type());
        
        let mut buffer = vec![0u8; 1024];
        
        // 协议层内部循环 - 这是关键设计！
        while stream.is_connected() {
            // 1. 从NetworkStream读取数据
            match stream.read(&mut buffer) {
                Ok(0) => {
                    println!("📡 连接 {} 已关闭", self.connection_id);
                    break;
                }
                Ok(n) => {
                    let data = &buffer[..n];
                    println!("📥 连接 {} 收到数据: {} bytes", self.connection_id, n);
                    
                    // 2. 协议层解析数据
                    self.parser.feed_data(data);
                    
                    // 3. 解析命令并立即响应
                    if let Some(command) = self.parser.parse_command() {
                        println!("📝 连接 {} 解析命令: {}", self.connection_id, command);
                        
                        // 4. 执行命令并生成响应
                        let response = match command.as_str() {
                            "PING" => b"+PONG\r\n".to_vec(),
                            "SET" => b"+OK\r\n".to_vec(),
                            "GET" => b"$5\r\nvalue\r\n".to_vec(),
                            _ => b"-ERR Unknown command\r\n".to_vec(),
                        };
                        
                        // 5. 通过NetworkStream写回响应
                        if let Err(e) = stream.write(&response) {
                            return Err(format!("写入响应失败: {}", e));
                        }
                        
                        if let Err(e) = stream.flush() {
                            return Err(format!("刷新失败: {}", e));
                        }
                        
                        println!("✅ 连接 {} 命令 {} 处理完成", self.connection_id, command);
                    }
                }
                Err(e) => {
                    return Err(format!("读取失败: {}", e));
                }
            }
        }
        
        println!("✅ 连接 {} 协议处理完成", self.connection_id);
        Ok(())
    }
    
    fn connection_id(&self) -> u64 { self.connection_id }
    fn runtime_type(&self) -> &'static str { self.runtime.lightweight_type() }
}

/// 演示协议层入口函数
fn main() {
    println!("🎨 协议层入口函数验证程序");
    println!("================================================================");
    println!("验证协议层直接接收NetworkStream并内部循环处理的设计\n");
    
    // 演示1：完整的协议层入口函数调用
    println!("🚀 演示：完整的协议层入口函数调用流程");
    
    // 1. 网络层创建具体的NetworkStream实现
    println!("1️⃣ 网络层创建TCP网络流...");
    let tcp_stream = MockTcpStream::new("127.0.0.1:6379".to_string());
    let stream_box: Box<dyn NetworkStream> = Box::new(tcp_stream);
    
    // 2. 网络层创建运行时
    println!("2️⃣ 网络层创建运行时...");
    let runtime = ThreadPoolRuntime;
    
    // 3. 网络层创建协议处理器
    println!("3️⃣ 网络层创建协议处理器...");
    let mut protocol_handler = ProtocolHandler::new(1, runtime);
    
    // 4. 🎯 关键：网络层调用协议层入口函数！
    println!("4️⃣ 🎯 网络层调用协议层入口函数：handle_connection_stream()");
    println!("   参数：Box<dyn NetworkStream> - 抽象的网络流");
    println!("   效果：协议层接管所有后续处理");
    
    match protocol_handler.handle_connection_stream(stream_box) {
        Ok(()) => {
            println!("✅ 协议层处理成功完成");
        }
        Err(e) => {
            println!("❌ 协议层处理失败: {}", e);
        }
    }
    
    println!("\n📊 演示结果:");
    println!("  连接ID: {}", protocol_handler.connection_id());
    println!("  运行时: {}", protocol_handler.runtime_type());
    
    println!("\n🎯 关键设计验证:");
    println!("  ✅ 协议层入口函数：handle_connection_stream()");
    println!("  ✅ 参数类型：Box<dyn NetworkStream>");
    println!("  ✅ 协议层内部循环：while stream.is_connected()");
    println!("  ✅ 网络层职责：创建具体实现 + 调用入口函数");
    println!("  ✅ 协议层职责：接管循环 + 解析 + 执行 + 响应");
    
    println!("\n🏆 架构优势:");
    println!("  1. 🔧 清晰的职责分离");
    println!("  2. 🎯 协议层完全控制处理流程");
    println!("  3. 📦 网络层只需提供抽象实现");
    println!("  4. 🔄 避免频繁的函数调用开销");
    println!("  5. ✨ 完美的抽象 - 协议层不知道具体网络实现");
    
    println!("\n🚀 这就是正确的协议层入口函数设计！");
    println!("   handle_connection_stream(stream: Box<dyn NetworkStream>)");
}